package com.hzqy.service.ift;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzqy.persistence.dao.itf.YxtDao;
import com.hzqy.service.core.GenericServiceBean;
import com.hzqy.web.vo.CmContentVo;
import com.hzqy.web.vo.PmsOrgVo;
import com.hzqy.web.vo.YxtAcountInfoVo;

@Service
public class YxtServiceBean extends GenericServiceBean<CmContentVo, YxtDao, Integer>{

	private static final long serialVersionUID = 1L;
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	
	
	private static final int YXT_SCHOOL_ID = 23;
	private static final int JYT_ID = 22;
	
	@Resource
	private YxtDao yxtDao;

	@Resource
	private ItfServiceBean itfServiceBean;
	
	@Override
	public YxtDao getEntityDao() {
		return yxtDao;
	}
	
	
	public Map<String, Object> updateServerAccount(String serverid, String account, String appkey, String stat, String msg){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		StringBuffer str = new StringBuffer();
		int flag = 0;
		// && StringUtils.isNotEmpty(stat)
		if(StringUtils.isNotEmpty(serverid) && StringUtils.isNotEmpty(account) && StringUtils.isNotEmpty(appkey) && StringUtils.isNotEmpty(msg)){
			if("itv2".equals(appkey)){
				JSONObject jsonObj = JSONObject.parseObject(msg);
				String msgcode = jsonObj.getString("msgcode");
				if("0000".equals(msgcode)){
					
					//更新cm_content.f_cc_code
					flag = yxtDao.updateServerAccount(serverid, account);
					
					if(flag > 0){
						List<YxtAcountInfoVo> aiList = yxtDao.selectYxtAccountInfoList(account);
						List<String> aiUseridList = new ArrayList<String>();
						for(YxtAcountInfoVo ai : aiList){
							aiUseridList.add(ai.getF_yai_userid());
						}
						
						JSONArray jsonMsg = jsonObj.getJSONArray("msg");
						int totalCount = jsonMsg.size();//接口获取总记录数量
						int insertCount = 0;//入库数量
						int updateCount = 0;//修改数量
						
						for(int i=0;i<jsonMsg.size();i++){
							JSONObject jsonAccount = jsonMsg.getJSONObject(i);
							YxtAcountInfoVo accountInfoVo = new YxtAcountInfoVo();
							accountInfoVo.setF_yai_account(account);
							accountInfoVo.setF_yai_status(1);
							accountInfoVo.setF_yai_stat(stat);
							accountInfoVo.setF_yai_course(jsonAccount.getString("course"));
							accountInfoVo.setF_yai_email(jsonAccount.getString("email"));
							accountInfoVo.setF_yai_logo(jsonAccount.getString("logo"));
							accountInfoVo.setF_yai_orgid(jsonAccount.getString("orgid"));
							accountInfoVo.setF_yai_orgname(jsonAccount.getString("orgname"));
							accountInfoVo.setF_yai_orgtype(jsonAccount.getString("orgtype"));
							accountInfoVo.setF_yai_porgid(jsonAccount.getString("porgid"));
							accountInfoVo.setF_yai_porgname(jsonAccount.getString("porgname"));
							accountInfoVo.setF_yai_porgtype(jsonAccount.getString("porgtype"));
							accountInfoVo.setF_yai_schoolname(jsonAccount.getString("schoolname"));
							accountInfoVo.setF_yai_schoolid(jsonAccount.getString("schoolid"));
							accountInfoVo.setF_yai_secondtype(jsonAccount.getString("secondtype"));
							accountInfoVo.setF_yai_phone(jsonAccount.getString("phone"));
							accountInfoVo.setF_yai_userid(jsonAccount.getString("userid"));
							accountInfoVo.setF_yai_username(jsonAccount.getString("username"));
							accountInfoVo.setF_yai_userrole(jsonAccount.getString("userrole"));
							accountInfoVo.setF_yai_usertype(jsonAccount.getString("usertype"));
							accountInfoVo.setF_yai_areaname(jsonAccount.getString("areaname"));
							accountInfoVo.setF_yai_districts(jsonAccount.getString("districts"));
							accountInfoVo.setF_yai_gradeid(jsonAccount.getString("grade2"));
							accountInfoVo.setF_yai_classid(jsonAccount.getString("classid"));
							accountInfoVo.setF_yai_classname(jsonAccount.getString("classname"));
							
							int idx = aiUseridList.indexOf(accountInfoVo.getF_yai_userid());
							//匹配用户信息, 如果存在, 则更新用户, 否则插入新数据
							if(idx >= 0){
								aiUseridList.remove(idx);
								YxtAcountInfoVo accountInfoBefore = aiList.remove(idx);
								accountInfoVo.setF_yai_id(accountInfoBefore.getF_yai_id());
								yxtDao.updateAccountInfo(accountInfoVo);
								updateCount++;
							}else{
								yxtDao.insertAccountInfo(accountInfoVo);
								insertCount++;
							}
						}
						
						//删除多余的用户
						for(YxtAcountInfoVo ai : aiList){
							yxtDao.deleteAccountByid(ai.getF_yai_id());
						}
						
						//schoolname对应的组织如果存在，将帐号绑定至此组织下面, 协议规定会数组里只有一个用户, 但程序意义上只取第一个用户的schoolname
						String bindStr = "";
						if(jsonMsg.size() > 0){
							String schoolname = jsonMsg.getJSONObject(0).getString("schoolname");
							bindStr += "本次注入用户学校: " + schoolname + "。 ";
							PmsOrgVo org = yxtDao.selectOrgByName(schoolname);
							int bindFlag = 0;
							if(org != null){//只要开过户，就要绑定
								bindFlag = yxtDao.updateServeridBindOrg(serverid, org.getF_po_id());
								bindStr += "此学校已开户, 更新帐号: " + serverid + "绑定关系, 更新 " + bindFlag + " 条记录"; 
							}else{//未开户
								bindStr += "此学校并未在校园平台开户, ";
								if("1".equals(stat)){
									bindFlag = yxtDao.updateServeridBindOrg(serverid, YXT_SCHOOL_ID);
									bindStr += "是翼校通用户, 将帐号绑定至翼校通学校, 更新帐号: " + serverid + "绑定关系, 更新 " + bindFlag + " 条记录";
								}else if("2".equals(stat)){
									bindFlag = yxtDao.updateServeridBindOrg(serverid, JYT_ID);
									bindStr += "非翼校通用户, 将帐号绑定至教育厅学校, 更新帐号: " + serverid + "绑定关系, 更新 " + bindFlag + " 条记录";
								}else{
									bindStr += "未知用户类型: " + stat + ", 不做任何绑定";
								}
							}
						}else{
							bindStr += "本次注入无用户信息";
						}
						LOG.debug("翼校通学校用户回调: 本次执行获取 " + totalCount + " 条记录, 入库 " + insertCount + " 条记录 更新 " + updateCount + " 条记录。" + bindStr);
					}else{
						flag = -4;
						str.append("数据有误, serverid:" + serverid + "不存在!");
					}
				}else{
					flag = -3;
					str.append("返回错误code:" +msgcode);
				}
			}else{
				flag = -2;
				str.append("校验失败, appkey:" + appkey);
			}
		}else{
			flag = -1;
			str.append("缺少参数");
		}
		
		if(flag > 0){
			str.append("成功");
			resultMap.put("success", "true");
		}else{
			resultMap.put("success", "false");
		}
		
		resultMap.put("flag", flag);
		resultMap.put("msg", str.toString());
		return resultMap;
	}

	
	
	public static final Map<Integer, String> CONTENT_STATUS = new HashMap<Integer, String>();
	static{
		CONTENT_STATUS.put(1, "online,已上线");
		CONTENT_STATUS.put(2, "wait_review,待审核");
		CONTENT_STATUS.put(3, "deleted,内容已删除");
		CONTENT_STATUS.put(4, "review_fail,审核不通过");
		CONTENT_STATUS.put(5, "wait_zm,等待发起转码");
		CONTENT_STATUS.put(6, "on_zm,正在转码");
		CONTENT_STATUS.put(7, "zm_fail,转码失败");
		CONTENT_STATUS.put(8, "on_download,正在下载资源");
		CONTENT_STATUS.put(9, "missing_res,资源缺失");
		CONTENT_STATUS.put(10, "res_error,资源格式/容量不正确");
	}
	

	public Map<String, Object> getContentStatus(String id) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		if(StringUtils.isNotEmpty(id) && !"null".equals(id)){
			CmContentVo content = yxtDao.selectContentByYxtId(id);
			if(content != null){
				String statusMsg = CONTENT_STATUS.get(Integer.valueOf(content.getF_cc_status()));
				if(statusMsg != null){
					String[] msgArr = statusMsg.split("\\,");
					returnMap.put("success", "1");
					returnMap.put("statuscode", msgArr[0]);
					returnMap.put("statusmsg", msgArr[1]);
					if("on_zm".equals(msgArr[0])){
						Map<String, Object> zmMap = itfServiceBean.getZmjdQueue(content.getF_cc_id());
						String success = String.valueOf(zmMap.remove("success"));
						String msg = String.valueOf(zmMap.remove("msg"));
						returnMap.put("zm_success", success);
						returnMap.put("zm_errormsg", msg);
						if("1".equals(success)){
							returnMap.putAll(zmMap);
						}
					}
				}else{
					returnMap.put("success", "0");
					returnMap.put("errormsg", "未知状态" + content.getF_cc_status());
				}
			}else{
				returnMap.put("success", "0");
				returnMap.put("errormsg", "id不存在:" + id);
			}
		}else{
			returnMap.put("success", "0");
			returnMap.put("errormsg", "id不能为空");
		}
		return returnMap;
	}
	
	
}
